package me.hyman.testcustomview.progressbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ProgressBar;

import me.hyman.testcustomview.R;

/**
 * Created by luluteam on 2016/9/27.
 */
public class HorizontalProgressBarWithNumber extends ProgressBar {

    private static final int DEFAULT_TEXT_SIZE = 10;
    private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1;
    private static final int DEFAULT_COLOR_UNREACHED = 0XFFD3D6DA;
    private static final int DEFAULT_HEIGHT_REACHED = 2;
    private static final int DEFAULT_HEIGHT_UNREACHED = 2;
    private static final int DEFAULT_SIZE_TEXT_OFFSET = 10;

    protected Paint mPaint = new Paint();
    protected int mTextColor = DEFAULT_TEXT_COLOR;
    protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE);
    protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET);
    protected int mReachedPBHeight = dp2px(DEFAULT_HEIGHT_REACHED);
    protected int mReachedPBColor = DEFAULT_TEXT_COLOR;
    protected int mUnReachedPBHeight = dp2px(DEFAULT_HEIGHT_UNREACHED);
    protected int mUnReachedPBColor = DEFAULT_COLOR_UNREACHED;

    protected int mRealWidth;
    protected boolean mIfDrawText = true;
    protected static final int VISIBLE = 0;


    public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        obtainStyledAttributes(attrs);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width, height);

        mRealWidth = getMeasuredWidth() - getPaddingRight() - getPaddingLeft();
    }

    private int measureHeight(int heightMeasureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        if(specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            float textHeight = mPaint.descent() - mPaint.ascent();
            result = (int) (getPaddingTop() + getPaddingBottom() +
                                Math.max(Math.max(mReachedPBHeight, mUnReachedPBHeight), Math.abs(textHeight)));
            if(specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }

        return result;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {

        canvas.save();
        //画笔平移到指定paddingLeft， getHeight()，以后坐标都为以此为0，0
        canvas.translate(getPaddingLeft(), getHeight() / 2);

        boolean noNeedBg = false;
        float ratio = getProgress() * 1.0f / getMax();
        float progressPosX = mRealWidth * ratio;
        String text = getProgress() + "%";

        float textWidth = mPaint.measureText(text);
        float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;

        //如果到达最后，则未到达的进度条不需要绘制（用来显示文本）
        if(progressPosX + textWidth > mRealWidth) {
            progressPosX = mRealWidth - textWidth;
            noNeedBg = true;
        }

        // 绘制已到达的进度
        float endX = progressPosX - mTextOffset / 2;
        if(endX > 0) {
            mPaint.setColor(mReachedPBColor);
            mPaint.setStrokeWidth(mReachedPBHeight);
            canvas.drawLine(0, 0, endX, 0, mPaint);
        }

        if(mIfDrawText) {
            mPaint.setColor(mTextColor);
            canvas.drawText(text, progressPosX, -textHeight, mPaint);
        }

        // 绘制未到达的进度条
        if(!noNeedBg) {
            float start = progressPosX + mTextOffset / 2 + textWidth;
            mPaint.setColor(mUnReachedPBColor);
            mPaint.setStrokeWidth(mUnReachedPBHeight);
            canvas.drawLine(start, 0, mRealWidth, 0, mPaint);
        }

        canvas.restore();
    }

    private void obtainStyledAttributes(AttributeSet attrs) {

        TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.HorizontalProgressBarWithNumber);

        mTextColor = attributes.getColor(R.styleable.HorizontalProgressBarWithNumber_progress_text_color, DEFAULT_TEXT_COLOR);
        mTextSize = (int) attributes.getDimension(
                R.styleable.HorizontalProgressBarWithNumber_progress_text_size,
                mTextSize);

        mReachedPBColor = attributes.getColor(
                        R.styleable.HorizontalProgressBarWithNumber_progress_reached_color,
                        mTextColor);
        mUnReachedPBColor = attributes.getColor(
                        R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color,
                DEFAULT_COLOR_UNREACHED);
        mReachedPBHeight = (int) attributes.getDimension(
                        R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height,
                        mReachedPBHeight);
        mUnReachedPBHeight = (int) attributes.getDimension(
                        R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height,
                        mUnReachedPBHeight);
        mTextOffset = (int) attributes.getDimension(
                        R.styleable.HorizontalProgressBarWithNumber_progress_text_offset,
                        mTextOffset);

        int textVisible = attributes.getInt(R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility, VISIBLE);
        if(textVisible != VISIBLE) {
            mIfDrawText = false;
        }
        attributes.recycle();
    }


    protected int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics());
    }

    protected int sp2px(int spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }
}
